#include "gamewindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTime>
#include <QRandomGenerator>
#include <algorithm>

GameWindow::GameWindow(QWidget* parent)
    : QMainWindow(parent)
{
    setupUI();
    initializeDeck();
}

void GameWindow::setupUI() {
    QWidget* central = new QWidget(this);
    QVBoxLayout* layout = new QVBoxLayout(central);
    QHBoxLayout* stacksLayout = new QHBoxLayout();
    layout->addLayout(stacksLayout);

    for (int i = 0; i < 10; ++i) {
        CardStack* stack = new CardStack(this);
        stack->setSpacing(25);
        stack->setMinimumSize(90, 600);
        stacksLayout->addWidget(stack);
        m_stacks.append(stack);
    }

    m_dealButton = new QPushButton("发牌");
    layout->addWidget(m_dealButton);
    connect(m_dealButton, &QPushButton::clicked, this, &GameWindow::dealCards);

    setCentralWidget(central);
}

void GameWindow::initializeDeck() {
    for (int i = 0; i < 8; ++i) {
        for (int val = 1; val <= 13; ++val) {
            m_deck.append(new Card(val));
        }
    }

    std::shuffle(m_deck.begin(), m_deck.end(), *QRandomGenerator::global());

    for (int i = 0; i < 10; ++i) {
        int numCards = (i < 4) ? 6 : 5;
        for (int j = 0; j < numCards; ++j) {
            Card* card = m_deck.takeFirst();
            m_stacks[i]->addCard(card);
            card->setFaceUp(j == numCards - 1);
        }
    }

    m_dealButton->setText(QString("发牌 (剩余: %1)").arg(m_deck.size()));
}


void GameWindow::dealCards() {
    if (m_deck.size() < 10)
        return;

    for (int i = 0; i < 10; ++i) {
        Card* card = m_deck.takeFirst();
        m_stacks[i]->addCard(card);
        card->setFaceUp(true);
    }

    m_dealButton->setText(QString("发牌 (剩余: %1)").arg(m_deck.size()));
    checkCompleteSequences();
}

void GameWindow::checkCompleteSequences() {
    for (CardStack* stack : std::as_const(m_stacks)) {
        QVector<Card*> cards = stack->cards();
        if (cards.size() < 13)
            continue;

        QVector<Card*> toRemove;
        bool isSequential = true;

        for (int i = cards.size() - 1; i >= cards.size() - 13; --i) {
            if (!cards[i]->isFaceUp() || cards[i]->value() != cards[cards.size() - 1]->value() - (cards.size() - 1 - i)) {
                isSequential = false;
                break;
            }
            toRemove.prepend(cards[i]);
        }

        if (isSequential) {
            for (Card* card : toRemove) {
                stack->removeCard(card);
                card->deleteLater();
            }
            stack->flipTopCard();
        }
    }
}
